package com.linkage.seapeak.fragment;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.FileAdapter;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.ProCrDecReviewInfo;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.bean.ZQBaseProjectCrDecInfo;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.EditTextChangedListenerAdapter;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.seapeak.activity.user.ImageShowActivity;
import com.linkage.seapeak.base.BaseFragment;
import com.linkage.seapeak.base.CommonBaseFragment;
import com.linkage.seapeak.pojo.UploadImage;
import com.linkage.seapeak.utils.CommonUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 填写审查意见
 */
public class ExamineAddDataFragment extends CommonBaseFragment {

    //
    @BindView(R.id.ly_declaration_detail)
    LinearLayout lyDeclarationDetail;

    //
    @BindView(R.id.ly_tax_declared_amount)
    RelativeLayout lyTaxDeclaredAmount;
    @BindView(R.id.tv_edit_normal_tax_1)
    TextView       tvEditNormalTax_1;
    @BindView(R.id.tv_edit_overdue_fine_1)
    TextView       tvEditOverdueFine_1;
    //
    @BindView(R.id.ly_normal_declared_amount)
    RelativeLayout lyNormalDeclaredAmount;
    @BindView(R.id.tv_edit_principal_1)
    TextView       tvEditPrincipal1;
    @BindView(R.id.tv_edit_interest_1)
    TextView       tvEditInterest1;

    //
    @BindView(R.id.tv_edit_other_1)
    TextView tvEditOther1;
    @BindView(R.id.tv_edit_total_amount_1)
    TextView tvEditTotalAmount1;
    @BindView(R.id.tv_edit_instructions_1)
    TextView tvEditInstructions1;


    @BindView(R.id.ly_no_tax_declare)
    RelativeLayout lyNoTaxDeclare;

    @BindView(R.id.tv_edit_priority_obligee_amount_1)
    TextView tvEditPriorityObligeeAmount1;
    @BindView(R.id.tv_edit_other_obligee_amount_1)
    TextView tvEditOtherObligeeAmount1;
    @BindView(R.id.tv_edit_obligee_instructions_1)
    TextView tvEditObligeeInstructions1;

    @BindView(R.id.recycler_files_ruling)
    RecyclerView mRecyclerViewFuling;
    @BindView(R.id.tv_ruling)
    TextView     tvRuling;

    @BindView(R.id.tv_edit_review_result_1)
    TextView tvEditReviewResult1;
    @BindView(R.id.tv_edit_supplement_info_1)
    TextView tvEditSupplementInfo1;

    @BindView(R.id.tv_title51)
    TextView mTv_title51;

    @BindView(R.id.tv_edit_supplement_info_11)
    TextView tvEditSupplementInfo11;



    @BindView(R.id.recycler_edit_tip)
    RecyclerView mRecyclerViewTip;

    @BindView(R.id.recycler_3)
    RecyclerView mRecycler_3;

    @BindView(R.id.tv_recycler_3)
    TextView mTv_recycler_3;


    @BindView(R.id.tv_edit_tip_info_1)
    TextView     tvEditTipInfo1;
    //
    @BindView(R.id.tv_info_title)
    TextView     tvInfoTitle;
    @BindView(R.id.show_info)
    LinearLayout showInfo;

    @BindView(R.id.tv_examine_money_tip)
    TextView tvExamineMoneyTip;
    @BindView(R.id.edit_confirm_amount)
    EditText editConfirmAmount;

    @BindView(R.id.ly_normal_examine)
    LinearLayout lyNormalExamine;
    @BindView(R.id.edit_ordinary_credit_amount)
    EditText     editOrdinaryCreditAmount;
    @BindView(R.id.edit_guaranteed_amount)
    EditText     editGuaranteedAmount;
    @BindView(R.id.edit_other_amount)
    EditText     editOtherAmount;


    @BindView(R.id.ly_tax_examine)
    LinearLayout lyTaxExamine;
    @BindView(R.id.edit_normal_tax)
    EditText     editNormalTax;
    @BindView(R.id.edit_late_payment)
    EditText     editLatePayment;
    @BindView(R.id.edit_other)
    EditText     editOther;


    @BindView(R.id.edit_no_confirm_amount)
    EditText editNoConfirmAmount;
    @BindView(R.id.edit_pending_amount)
    EditText editPendingAmount;

    @BindView(R.id.edit_review_result)
    EditText editReviewResult;
    @BindView(R.id.eidt_supplement_info)
    EditText eidtSupplementInfo;
    @BindView(R.id.edit_tip)
    EditText editTip;

    @BindView(R.id.ly_tip)
    LinearLayout lyTip;



    //传入数据
    private String mProjectId;
    private String mReviewId;
    private String mCreditorRightsId;

    //提交后返回数据
    private String mDataReviewId;
    private String mDataCreditorRightsId;

    private String mReEditData;//上个界面带入的数据

    private String mDeclareAmountTotal;

    private onSendNotifyListener mOnSendNotifyListener;

    private boolean isFirstEdit;//true:初次填写  false:重新填写
    private boolean isModify;
    private boolean isTaxMode               = true;//true：税务机关债券；false：一般债券人
    private boolean isReplenishOrReviewPage = false;//true:补充 或 重新审查 类型

    public void setOnSendNotifyListener( onSendNotifyListener mOnSendNotifyListener ) {
        this.mOnSendNotifyListener = mOnSendNotifyListener;
    }

    public void setFirstEdit( boolean firstEdit ) {
        isFirstEdit = firstEdit;
    }

    public void setReEditData( String mReEditData ) {
        this.mReEditData = mReEditData;
    }

    public String getDataReviewId() {
        return mDataReviewId;
    }

    public void setDataReviewId( String mDataReviewId ) {
        this.mDataReviewId = mDataReviewId;
    }

    public String getDataCreditorRightsId() {
        return mDataCreditorRightsId;
    }

    public void setDataCreditorRightsId( String mDataCreditorRightsId ) {
        this.mDataCreditorRightsId = mDataCreditorRightsId;
    }

    public static ExamineAddDataFragment getInstance( boolean isTaxMode, boolean isReplenishOrReviewPage, String mProjectId, String mReviewId, String mCreditorRightsId ) {
        ExamineAddDataFragment fragment = new ExamineAddDataFragment();
        fragment.isTaxMode = isTaxMode;
        fragment.isReplenishOrReviewPage = isReplenishOrReviewPage;
        fragment.mProjectId = mProjectId;
        fragment.mReviewId = mReviewId;
        fragment.mCreditorRightsId = mCreditorRightsId;
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_examine_creditor;
    }

    @Override
    protected void initVariable( Bundle savedInstanceState ) {
        super.initVariable(savedInstanceState);
    }

    @Override
    public void initViews() {
        super.initViews();
        setEditContentListener();
        if (isReplenishOrReviewPage) {
            lyTip.setVisibility(View.VISIBLE);
        }
        if (isTaxMode) {
            lyTaxDeclaredAmount.setVisibility(View.VISIBLE);
            lyNormalDeclaredAmount.setVisibility(View.GONE);

            lyNoTaxDeclare.setVisibility(View.GONE);
        }
    }

    @Override
    public void initData() {
        super.initData();
        getDetailInfo();
    }

    @OnClick(R.id.show_info)
    public void onViewClicked() {
        if ("查看申报信息".equals(tvInfoTitle.getText().toString())) {
            changeLookStatus("收起", R.mipmap.icon_arrow_up);
            lyDeclarationDetail.setVisibility(View.VISIBLE);
        } else {
            changeLookStatus("查看申报信息", R.mipmap.icon_arrow_down);
            lyDeclarationDetail.setVisibility(View.GONE);
        }
    }

    private void changeLookStatus( String title, int resId ) {
        tvInfoTitle.setText(title);
        Drawable drawable = getResources().getDrawable(resId);
        tvInfoTitle.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
        tvInfoTitle.setCompoundDrawablePadding(0);
    }


    public void getDetailInfo() {
        if (TextUtils.isEmpty(getUserToken()) || TextUtils.isEmpty(mProjectId)) return;
        Network.getAPIService().gethDeclarationDetail(getUserToken(), mProjectId, mCreditorRightsId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext( JsonObject json ) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            showToast(json.get("msg").getAsString());
                            return;
                        } else {
                            //债权申报信息
                            ZQBaseProjectCrDecInfo reviewInfo = new Gson().fromJson(json.getAsJsonObject("data").get("projectCrDec"),
                                                                                    ZQBaseProjectCrDecInfo.class);
                            showDeclarationDetail(reviewInfo);
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError( Throwable e ) {
                        super.onError(e);
                    }
                });
    }

    private void showDeclarationDetail( ZQBaseProjectCrDecInfo data ) {
        if (data == null) return;

        if(data.getReview()!=null)
        {
            if (isTaxMode) {
//                editNormalTax.setText("111");
//                editLatePayment.setText("222");
//                editOther.setText("333");
                editNormalTax.setText(CommonUtils.resetMoney_nodot(data.getReview().getRegularTaxMoney()));
                editLatePayment.setText(CommonUtils.resetMoney_nodot(data.getReview().getOverdueFineMoney()));
                editOther.setText(CommonUtils.resetMoney_nodot(data.getReview().getOtherMoney()));
            }else{
                editOrdinaryCreditAmount.setText(CommonUtils.resetMoney_nodot(data.getReview().getOrdinaryMoney()));
                editGuaranteedAmount.setText(CommonUtils.resetMoney_nodot(data.getReview().getGuaranteePriority()));
                editOtherAmount.setText(CommonUtils.resetMoney_nodot(data.getReview().getOtherPriorityMoney()));
            }

            editNoConfirmAmount.setText(CommonUtils.resetMoney_nodot(data.getReview().getDisconfirmationMoney()));
            editPendingAmount.setText(CommonUtils.resetMoney_nodot(data.getReview().getUndeterminedMoney()));
            editReviewResult.setText(data.getReview().getReviewResults());
            eidtSupplementInfo.setText(data.getReview().getSupplementaryMaterial());
            editTip.setText(data.getReview().getSpecialNote());

        }else if(data.getPreVersion()!=null){
            if (isTaxMode) {
                editNormalTax.setText(CommonUtils.resetMoney_nodot(data.getPreVersion().getReview().getRegularTaxMoney()));
                editLatePayment.setText(CommonUtils.resetMoney_nodot(data.getPreVersion().getReview().getOverdueFineMoney()));
                editOther.setText(CommonUtils.resetMoney_nodot(data.getPreVersion().getReview().getOtherMoney()));
            }else{
                editOrdinaryCreditAmount.setText(CommonUtils.resetMoney_nodot(data.getPreVersion().getReview().getOrdinaryMoney()));
                editGuaranteedAmount.setText(CommonUtils.resetMoney_nodot(data.getPreVersion().getReview().getGuaranteePriority()));
                editOtherAmount.setText(CommonUtils.resetMoney_nodot(data.getPreVersion().getReview().getOtherPriorityMoney()));
            }

            editNoConfirmAmount.setText(CommonUtils.resetMoney_nodot(data.getPreVersion().getReview().getDisconfirmationMoney()));
            editPendingAmount.setText(CommonUtils.resetMoney_nodot(data.getPreVersion().getReview().getUndeterminedMoney()));
            editReviewResult.setText(data.getPreVersion().getReview().getReviewResults());
            eidtSupplementInfo.setText(data.getPreVersion().getReview().getSupplementaryMaterial());
            editTip.setText(data.getPreVersion().getReview().getSpecialNote());
        }
            mDeclareAmountTotal = data.getDeclareAmountTotal();

            //申报金额
            if (isTaxMode) {
                tvEditNormalTax_1.setText(formatAmount(data.getDeclareAmountRegularTax()));
                tvEditOverdueFine_1.setText(formatAmount(data.getDeclareAmountOverdueFine()));
            } else {
                tvEditPrincipal1.setText(formatAmount(data.getDeclareAmountPrincipal()));
                tvEditInterest1.setText(formatAmount(data.getDeclareAmountInterest()));
            }
            tvEditOther1.setText(formatAmount(data.getDeclareAmountOther()));
            tvEditTotalAmount1.setText(formatAmount(mDeclareAmountTotal));
            tvEditInstructions1.setText("");

            if (!isTaxMode) {
                //优先债权主张和说明
                tvEditPriorityObligeeAmount1.setText(formatAmount(data.getGuaranteePriority()));
                tvEditOtherObligeeAmount1.setText(formatAmount(data.getOtherPriority()));
                tvEditObligeeInstructions1.setText(data.getPreferredCreditorRightsDetail());
            }

            //生效判决/裁决
            List<TaskAtta> mImgList1 = new ArrayList<>();
             FileAdapter mImgAdapter1;

            List<TaskAtta> mImgList2 = new ArrayList<>();
        FileAdapter mImgAdapter2;

        List<TaskAtta> mImgList3 = new ArrayList<>();
        FileAdapter mImgAdapter3;

            List<TaskAtta> attas = data.getJudgmentAtta();
            if (attas != null && attas.size() > 0) {
                mRecyclerViewFuling.setVisibility(View.VISIBLE);
//            mRecyclerViewFuling.setLayoutManager(new LinearLayoutManager(getActivity()));
//            ImageAdapter imageAdapter = new ImageAdapter(attas);
//            mRecyclerViewFuling.setAdapter(imageAdapter);


                mRecyclerViewFuling.setNestedScrollingEnabled(false);

                mImgAdapter1 = new FileAdapter(getActivity(), mImgList1);
                mRecyclerViewFuling.setLayoutManager(mImgAdapter1.createLayoutManager());
                mRecyclerViewFuling.setAdapter(mImgAdapter1);
                mImgList1.clear();
                mImgList1.addAll(attas);
//                if (info.getProvideBusinessLicenseAttas() != null) {
//                    mImgList1.addAll(attas);

//                }

//                FullyGridLayoutManager manager = new FullyGridLayoutManager(getActivity(), 4, GridLayoutManager.VERTICAL, false);
//                mRecyclerViewFuling.setLayoutManager(manager);
//                mImgAdapter1 = new BaseFragment.GridImagesAdapter(getActivity(), TYPE_PREVIEW);
//                mImgList1.clear();
//                mImgAdapter1.setList(mImgList1);
//                mRecyclerViewFuling.setAdapter(mImgAdapter1);
//
//
//                for (int i = 0; i < attas.size(); i++) {
//                    TaskAtta atta = attas.get(i);
//                    JSONObject obj = new JSONObject();
//                    try {
//                        obj.putOpt("filename", atta.getAttachmentName());
//                        obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
//                        obj.putOpt("filesize", atta.getAttachmentSize());
//                        obj.putOpt("loadUrl", atta.getAttachmentThumbnailAddress());
//                        mImgList1.add(new Gson().fromJson(obj.toString(), UploadImage.class));
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }

            } else {
                tvRuling.setVisibility(View.VISIBLE);
                tvRuling.setText("无");
            }

        List<TaskAtta> attas1 = data.getExecutionAtta();
        if (attas1 != null && attas1.size() > 0) {
            mRecycler_3.setVisibility(View.VISIBLE);

            mRecycler_3.setNestedScrollingEnabled(false);

            mImgAdapter3 = new FileAdapter(getActivity(), mImgList3);
            mRecycler_3.setLayoutManager(mImgAdapter3.createLayoutManager());
            mRecycler_3.setAdapter(mImgAdapter3);
            mImgList3.clear();
            mImgList3.addAll(attas1);
//            FullyGridLayoutManager manager = new FullyGridLayoutManager(getActivity(), 4, GridLayoutManager.VERTICAL, false);
//            mRecycler_3.setLayoutManager(manager);
//            mImgAdapter3 = new BaseFragment.GridImagesAdapter(getActivity(), TYPE_PREVIEW);
//            mImgList3.clear();
//            mImgAdapter3.setList(mImgList3);
//            mRecycler_3.setAdapter(mImgAdapter3);
//            mTv_recycler_3.setVisibility(View.GONE);
//
//            for (int i = 0; i < attas1.size(); i++) {
//                TaskAtta atta1 = attas1.get(i);
//                JSONObject obj = new JSONObject();
//                try {
//                    obj.putOpt("filename", atta1.getAttachmentName());
//                    obj.putOpt("filepath", atta1.getAttachmentDownloadAddress());
//                    obj.putOpt("filesize", atta1.getAttachmentSize());
//                    obj.putOpt("loadUrl", atta1.getAttachmentThumbnailAddress());
//                    mImgList3.add(new Gson().fromJson(obj.toString(), UploadImage.class));
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }

        } else {
            mTv_recycler_3.setVisibility(View.VISIBLE);
            mTv_recycler_3.setText("无");
        }



            //
            tvEditReviewResult1.setText(TextUtils.isEmpty(data.getExecutiveDetail()) ? "无" : data.getExecutiveDetail());//执行情况
            tvEditSupplementInfo1.setText(TextUtils.isEmpty(data.getCreditorRightsNote()) ? "无" : data.getCreditorRightsNote());//债权描述

            tvEditSupplementInfo11.setText(TextUtils.isEmpty(data.getSupplementExplain()) ? "无" : data.getSupplementExplain());
        //补充信息
        if(!"1".equalsIgnoreCase(data.getDeclareStatus().getValue()))
        {
            tvEditSupplementInfo11.setVisibility(View.GONE);
            mTv_title51.setVisibility(View.GONE);
        }else{
            tvEditSupplementInfo11.setVisibility(View.VISIBLE);
            mTv_title51.setVisibility(View.VISIBLE);
        }

            //申报文件
            List<TaskAtta> executionAttas = data.getOtherAtta();
            if (executionAttas != null && executionAttas.size() > 0) {
                mRecyclerViewTip.setVisibility(View.VISIBLE);
//            mRecyclerViewTip.setLayoutManager(new LinearLayoutManager(getActivity()));
//            ImageAdapter imageAdapter = new ImageAdapter(executionAttas);
//            mRecyclerViewTip.setAdapter(imageAdapter);
                mImgAdapter2 = new FileAdapter(getActivity(), mImgList2);
                mRecyclerViewTip.setLayoutManager(mImgAdapter2.createLayoutManager());
                mRecyclerViewTip.setAdapter(mImgAdapter2);
                mImgList2.clear();
                mImgList2.addAll(executionAttas);

//                FullyGridLayoutManager manager = new FullyGridLayoutManager(getActivity(), 4, GridLayoutManager.VERTICAL, false);
//                mRecyclerViewTip.setLayoutManager(manager);
//                mImgAdapter2 = new BaseFragment.GridImagesAdapter(getActivity(), TYPE_PREVIEW);
//                mImgList2.clear();
//                mImgAdapter2.setList(mImgList2);
//                mRecyclerViewTip.setAdapter(mImgAdapter2);
//
//
//                for (int i = 0; i < executionAttas.size(); i++) {
//                    TaskAtta atta = executionAttas.get(i);
//                    JSONObject obj = new JSONObject();
//                    try {
//                        obj.putOpt("filename", atta.getAttachmentName());
//                        obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
//                        obj.putOpt("filesize", atta.getAttachmentSize());
//                        obj.putOpt("loadUrl", atta.getAttachmentThumbnailAddress());
//                        mImgList2.add(new Gson().fromJson(obj.toString(), UploadImage.class));
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }

            } else {
                tvEditTipInfo1.setVisibility(View.VISIBLE);
                tvEditTipInfo1.setText("无");
            }

            if (isFirstEdit) {
                String tempLocalDataJson = SPUtils.getInstance(Consts.SPNAME).getString(mProjectId + BankruptcyApp.loginInfo.getId());

                if (!TextUtils.isEmpty(tempLocalDataJson)) {
                    ZQBaseProjectCrDecInfo localData = new Gson().fromJson(tempLocalDataJson, ZQBaseProjectCrDecInfo.class);
                    setLocalDataOfForm(localData);
                }
            } else {
//                setReReviewData(mReEditData);
            }

    }


    public void sendReviewData( int sendStatus ) {//sendStatus
        isModify = true;
        String confirmAmount = editConfirmAmount.getText().toString().trim();
        //
        String ordinaryCreditAmount = editOrdinaryCreditAmount.getText().toString().trim();
        String guaranteedAmount     = editGuaranteedAmount.getText().toString().trim();
        String otherAmount          = editOtherAmount.getText().toString().trim();
        //
        String normalTax   = editNormalTax.getText().toString().trim();
        String latePayment = editLatePayment.getText().toString().trim();
        String other       = editOther.getText().toString().trim();
        //
        String noConfirmAmount = editNoConfirmAmount.getText().toString().trim();
        String pendingAmount   = editPendingAmount.getText().toString().trim();
        //
        String reviewResult   = editReviewResult.getText().toString().trim();
        String supplementInfo = eidtSupplementInfo.getText().toString().trim();
        String tip            = editTip.getText().toString().trim();

        onCalculateAmount();

        if (TextUtils.isEmpty(getUserToken()) || TextUtils.isEmpty(mProjectId) || TextUtils.isEmpty(mCreditorRightsId) || TextUtils.isEmpty(confirmAmount)) {
            showToast("请检查信息完整");
            return;
        }

//        mReviewId="";
        Network.getAPIService().sendDeclarationReviewData(getUserToken(), mProjectId, mCreditorRightsId,
                                                          formatData(confirmAmount), formatData(ordinaryCreditAmount), formatData(guaranteedAmount), formatData(otherAmount),
                                                          formatData(noConfirmAmount), formatData(pendingAmount),
                                                          formatData(normalTax), formatData(latePayment), formatData(other),
                                                          reviewResult, supplementInfo, tip, sendStatus,mReviewId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext( JsonObject json ) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            showToast(json.get("msg").getAsString());
                            return;
                        } else {
                            JsonObject dataObject       = json.getAsJsonObject("data");
                            String     creditorRightsId = dataObject.get("creditorRightsId").getAsString();
                            String     crReviewId       = dataObject.get("crReviewId").getAsString();
                            String     creditorId       = dataObject.get("creditorId").getAsString();

                            setDataReviewId(crReviewId);
                            setDataCreditorRightsId(creditorRightsId);

                            LogUtil.e("tag:", String.format("creditorRightsId = %s |crReviewId = %s", creditorRightsId, crReviewId));

//                            SPUtils.getInstance(Consts.SPNAME).remove(mProjectId + BankruptcyApp.loginInfo.getId());
                            showToast("提交成功");

                            EventBus.getDefault().post("sendDataStatus");
                            if (mOnSendNotifyListener != null) {
                                mOnSendNotifyListener.onSendSuccess();
                            }
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError( Throwable e ) {
                        super.onError(e);
                        onLocalDataSave();
                        showToast("提交失败");
                        EventBus.getDefault().post("sendDataStatus");
                        if (mOnSendNotifyListener != null) {
                            mOnSendNotifyListener.onSendFailure();
                        }
                    }
                });
    }

    //重新审查
    public void sendReReviewData( int sendStatus ) {
        isModify = true;
        String confirmAmount = reFormatAmount(editConfirmAmount.getText().toString().trim());
        //
        String ordinaryCreditAmount = reFormatAmount(editOrdinaryCreditAmount.getText().toString().trim());
        String guaranteedAmount     = reFormatAmount(editGuaranteedAmount.getText().toString().trim());
        String otherAmount          = reFormatAmount(editOtherAmount.getText().toString().trim());
        //
        String normalTax   = reFormatAmount(editNormalTax.getText().toString().trim());
        String latePayment = reFormatAmount(editLatePayment.getText().toString().trim());
        String other       = reFormatAmount(editOther.getText().toString().trim());
        //
        String noConfirmAmount = reFormatAmount(editNoConfirmAmount.getText().toString().trim());
        String pendingAmount   = reFormatAmount(editPendingAmount.getText().toString().trim());
        //
        String reviewResult   = editReviewResult.getText().toString().trim();
        String supplementInfo = eidtSupplementInfo.getText().toString().trim();
        String tip            = editTip.getText().toString().trim();

        onCalculateAmount();

        if (TextUtils.isEmpty(getUserToken()) || TextUtils.isEmpty(mProjectId) || TextUtils.isEmpty(mReviewId) || TextUtils.isEmpty(mCreditorRightsId)) {
            showToast("请检查信息完整");
            return;
        }

        Network.getAPIService().sendDeclarationReReviewData(getUserToken(), mProjectId, mReviewId, mCreditorRightsId,
                                                            Double.valueOf(confirmAmount), Double.valueOf(ordinaryCreditAmount), Double.valueOf(guaranteedAmount), Double.valueOf(otherAmount),
                                                            Double.valueOf(noConfirmAmount), Double.valueOf(pendingAmount),
                                                            Double.valueOf(normalTax), Double.valueOf(latePayment), Double.valueOf(other),
                                                            reviewResult, supplementInfo, tip, sendStatus)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext( JsonObject json ) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            showToast(json.get("msg").getAsString());
                            return;
                        } else {
                            JsonObject dataObject       = json.getAsJsonObject("data");
                            String     creditorRightsId = dataObject.get("creditorRightsId").getAsString();
                            String     crReviewId       = dataObject.get("crReviewId").getAsString();
                            String     creditorId       = dataObject.get("creditorId").getAsString();

                            setDataReviewId(crReviewId);
                            setDataCreditorRightsId(creditorRightsId);

                            LogUtil.e("tag:", String.format("creditorRightsId = %s |crReviewId = %s", creditorRightsId, crReviewId));

                            SPUtils.getInstance(Consts.SPNAME).remove(mProjectId + BankruptcyApp.loginInfo.getId());
                            showToast("提交成功");
                            EventBus.getDefault().post("sendDataStatus");

                            if (mOnSendNotifyListener != null) {
                                mOnSendNotifyListener.onSendSuccess();
                            }
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError( Throwable e ) {
                        super.onError(e);
                        onLocalDataSave();
                        showToast("提交失败");
                        EventBus.getDefault().post("sendDataStatus");
                        if (mOnSendNotifyListener != null) {
                            mOnSendNotifyListener.onSendFailure();
                        }
                    }
                });
    }

    @SuppressLint("CheckResult")
    private void onCalculateAmount() {//计算确认金额
        if (!isModify) {
            tvExamineMoneyTip.setVisibility(View.GONE);
            return;
        }
        Observable.just("")
                .observeOn(io.reactivex.android.schedulers.AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    double confirmAmount;
                    if (isTaxMode) {

                        double normalTax   = formatData(editNormalTax.getText().toString().trim());
                        double latePayment = formatData(editLatePayment.getText().toString().trim());
                        double otherAmount = formatData(editOther.getText().toString().trim());

                        confirmAmount = normalTax + latePayment + otherAmount;

                    } else {

                        double ordinaryCreditAmount = formatData(editOrdinaryCreditAmount.getText().toString().trim());
                        double guaranteedAmount     = formatData(editGuaranteedAmount.getText().toString().trim());
                        double otherAmount          = formatData(editOtherAmount.getText().toString().trim());

                        confirmAmount = ordinaryCreditAmount + guaranteedAmount + otherAmount;

                    }
                    editConfirmAmount.setText(String.format("%.2f", confirmAmount));

                    double noConfirmAmount = formatData(editNoConfirmAmount.getText().toString().trim());
                    double pendingAmount   = formatData(editPendingAmount.getText().toString().trim());

                    double totalAmount        = confirmAmount + noConfirmAmount + pendingAmount;
                    double declareAmountTotal = formatData(mDeclareAmountTotal);
                    tvExamineMoneyTip.setVisibility(declareAmountTotal != totalAmount ? View.VISIBLE : View.GONE);
                });
    }

    private void setEditContentListener() {
        if (isTaxMode) {
            lyTaxExamine.setVisibility(View.VISIBLE);
            lyNormalExamine.setVisibility(View.GONE);
            addEditListener(editNormalTax);
            addEditListener(editLatePayment);
            addEditListener(editOther);

        } else {
            lyNormalExamine.setVisibility(View.VISIBLE);
            lyTaxExamine.setVisibility(View.GONE);
            addEditListener(editOrdinaryCreditAmount);
            addEditListener(editGuaranteedAmount);
            addEditListener(editOtherAmount);
        }

        addEditListener(editNoConfirmAmount);
        addEditListener(editPendingAmount);
    }

    private void addEditListener( EditText editView ) {
        editView.addTextChangedListener(new EditTextChangedListenerAdapter() {
            @Override
            public void onTextChanged( CharSequence charSequence, int i, int i1, int i2 ) {
                super.onTextChanged(charSequence, i, i1, i2);
                isModify = true;
                onCalculateAmount();
            }

            @Override
            public void afterTextChanged( Editable editable ) {

            }
        });
    }

    private String formatAmount( String amount ) {
        if (TextUtils.isEmpty(amount)) {
            amount = "0.00";
        }
        String  str = String.format("%s元", CommonUtils.resetMoney(amount));;

        return str;
    }

    private Double formatData( String data ) {
        if (TextUtils.isEmpty(data)) {
            return 0.00;
        }
        return Double.valueOf(data);
    }

    //进行保存已写入信息
    public void onLocalDataSave() {
        String confirmAmount = editConfirmAmount.getText().toString().trim();
        //
        String ordinaryCreditAmount = editOrdinaryCreditAmount.getText().toString().trim();
        String guaranteedAmount     = editGuaranteedAmount.getText().toString().trim();
        String otherAmount          = editOtherAmount.getText().toString().trim();
        //
        String normalTax   = editNormalTax.getText().toString().trim();
        String latePayment = editLatePayment.getText().toString().trim();
        String other       = editOther.getText().toString().trim();
        //
        String noConfirmAmount = editNoConfirmAmount.getText().toString().trim();
        String pendingAmount   = editPendingAmount.getText().toString().trim();
        //
        String reviewResult   = editReviewResult.getText().toString().trim();
        String supplementInfo = eidtSupplementInfo.getText().toString().trim();
        String tip            = editTip.getText().toString().trim();


        ZQBaseProjectCrDecInfo info = new ZQBaseProjectCrDecInfo();
        info.setConfirmedMoney(confirmAmount);
        if (isTaxMode) {
            info.setDeclareAmountRegularTax(normalTax);
            info.setDeclareAmountOverdueFine(latePayment);
            info.setDeclareAmountOther(other);

        } else {
            info.setOrdinaryMoney(ordinaryCreditAmount);
            info.setGuaranteePriority(guaranteedAmount);
            info.setOtherPriority(otherAmount);
        }
        info.setDisconfirmationMoney(noConfirmAmount);
        info.setUndeterminedMoney(pendingAmount);

        info.setReviewResults(reviewResult);
        info.setSupplementaryMaterial(supplementInfo);
        info.setSpecialNote(tip);

        SPUtils.getInstance(Consts.SPNAME).put(mProjectId + BankruptcyApp.loginInfo.getId(), new Gson().toJson(info));
    }

    //设置暂存数据
    private void setLocalDataOfForm( ZQBaseProjectCrDecInfo data ) {
        if (data != null) {
            if (isTaxMode) {
                if (equalsInitialValue(data.getConfirmedMoney()) && equalsInitialValue(data.getDeclareAmountRegularTax()) && equalsInitialValue(data.getDeclareAmountOverdueFine()) && equalsInitialValue(data.getDeclareAmountOther())
                        && TextUtils.isEmpty(data.getReviewResults()) && TextUtils.isEmpty(data.getSupplementaryMaterial()) && TextUtils.isEmpty(data.getSpecialNote())) {
                    isModify = false;
                    return;
                }

            } else {
                if (equalsInitialValue(data.getConfirmedMoney()) && equalsInitialValue(data.getOrdinaryMoney()) && equalsInitialValue(data.getGuaranteePriority()) && equalsInitialValue(data.getOtherPriority())
                        && TextUtils.isEmpty(data.getReviewResults()) && TextUtils.isEmpty(data.getSupplementaryMaterial()) && TextUtils.isEmpty(data.getSpecialNote())) {
                    isModify = false;
                    return;
                }
            }
            editOrdinaryCreditAmount.setText(data.getConfirmedMoney());
            if (isTaxMode) {
                editNormalTax.setText(data.getReview().getRegularTaxMoney());
                editLatePayment.setText(data.getReview().getOverdueFineMoney());
                editOther.setText(data.getReview().getOtherPriorityMoney());
            } else {
                editOrdinaryCreditAmount.setText(data.getReview().getOrdinaryMoney());
                editGuaranteedAmount.setText(data.getReview().getGuaranteePriority());
                editOtherAmount.setText(data.getReview().getOtherMoney());
            }
            editNoConfirmAmount.setText(data.getDisconfirmationMoney());
            editPendingAmount.setText(data.getUndeterminedMoney());

            editReviewResult.setText(data.getReviewResults());
            eidtSupplementInfo.setText(data.getSupplementaryMaterial());
            editTip.setText(data.getSpecialNote());

        } else {
            isModify = false;
        }
    }

    //重新审查带入的信息
    private void setReReviewData( String dataJson ) {
        if (TextUtils.isEmpty(dataJson)) {
            isModify = false;
            return;
        }
        JsonObject data = new Gson().fromJson(dataJson, JsonObject.class);
        if (data != null) {
            //债权申报信息
            ZQBaseProjectCrDecInfo projectCrDec = new Gson().fromJson(data.get("projectCrDec"), ZQBaseProjectCrDecInfo.class);
            //审查信息
            ProCrDecReviewInfo crDecRev = new Gson().fromJson(data.get("crDecRev"), ProCrDecReviewInfo.class);
            if (projectCrDec == null || crDecRev == null)
                return;

            if (isTaxMode) {
                if (equalsInitialValue(crDecRev.getConfirmedMoney()) && equalsInitialValue(projectCrDec.getDeclareAmountRegularTax()) && equalsInitialValue(projectCrDec.getDeclareAmountOverdueFine()) && equalsInitialValue(projectCrDec.getDeclareAmountOther())
                        && TextUtils.isEmpty(crDecRev.getReviewResults()) && TextUtils.isEmpty(crDecRev.getSupplementaryMaterial()) && TextUtils.isEmpty(crDecRev.getSpecialNote())) {
                    isModify = false;
                    return;
                }

            } else {
                if (equalsInitialValue(crDecRev.getConfirmedMoney()) && equalsInitialValue(crDecRev.getOrdinaryMoney()) && equalsInitialValue(crDecRev.getGuaranteePriority()) && equalsInitialValue(crDecRev.getOtherPriorityMoney())
                        && TextUtils.isEmpty(crDecRev.getReviewResults()) && TextUtils.isEmpty(crDecRev.getSupplementaryMaterial()) && TextUtils.isEmpty(crDecRev.getSpecialNote())) {
                    isModify = false;
                    return;
                }
            }
            editOrdinaryCreditAmount.setText(crDecRev.getConfirmedMoney());
            if (isTaxMode) {
                editNormalTax.setText(projectCrDec.getDeclareAmountRegularTax());
                editLatePayment.setText(projectCrDec.getDeclareAmountOverdueFine());
                editOther.setText(projectCrDec.getDeclareAmountOther());
            } else {
                editOrdinaryCreditAmount.setText(crDecRev.getOrdinaryMoney());
                editGuaranteedAmount.setText(crDecRev.getGuaranteePriority());
                editOtherAmount.setText(crDecRev.getOtherPriorityMoney());
            }
            editNoConfirmAmount.setText(crDecRev.getDisconfirmationMoney());
            editPendingAmount.setText(crDecRev.getUndeterminedMoney());

            editReviewResult.setText(crDecRev.getReviewResults());
            eidtSupplementInfo.setText(crDecRev.getSupplementaryMaterial());
            editTip.setText(crDecRev.getSpecialNote());

        } else {
            isModify = false;
        }
    }

    private boolean equalsInitialValue( String curValue ) {
        if (TextUtils.isEmpty(curValue)) {
            return true;
        } else {
            return "0.00".equals(String.format("%.2f", Float.valueOf(curValue)));
        }
    }

    public interface onSendNotifyListener {
        void onSendSuccess();

        void onSendFailure();
    }

    private String reFormatAmount( String oldData ) {
        return TextUtils.isEmpty(oldData) ? "0" : oldData.replace("元", "");
    }

    class ImageAdapter extends BaseQuickAdapter<TaskAtta, BaseViewHolder> {

        public ImageAdapter( @Nullable List<TaskAtta> list ) {
            super(R.layout.activity_pro_public_file_item, list);
        }

        @Override
        protected void convert( final BaseViewHolder helper, TaskAtta item ) {
            if (item == null) return;

            String suffix = item.getAttachmentSuffix();
//            helper.setText(R.id.tv_file_name, String.format("%s.%s", item.getAttachmentName(), suffix));
            helper.setText(R.id.tv_file_name,  item.getAttachmentName());

            String url = (String)item.getAttachmentThumbnailAddress();
            helper.getView(R.id.tv_file_name).setOnClickListener(v -> {
                if (suffix.equalsIgnoreCase("pdf")) {
                    BaseActivity.openOrDownloadFile(item, getActivity());
                } else {
                    ImageShowActivity.start(getActivity(), url, ImageShowActivity.FROM_MUlTI_SHOW);
                }
            });
        }
    }
}
